<script>
/**
 * @desc 旅游的套餐选择(弹出层)
 * 从这一步开始就需要将用户的选择信息存入store
 */

import { mapMutations } from 'vuex'

export default {
  name: 'package-select',
  props: {
    show: Boolean,
    handleClose: Function,
    packageList: Array
  },
  data() {
    console.log('init packgeList')
    return {
      list: this.packageList.map(v => ({ ...v, checked: false, count: 1 }))
    }
  },
  computed: {
    totalPrice() {
      return this.list.reduce((pre, curr) => {
        return curr.checked ? pre + curr.price * curr.count : pre
      }, 0)
    }
  },
  methods: {
    ...mapMutations('Order', ['setState']),
    handleCheck(id) {
      this.list = this.list.map(v => ({ ...v, checked: v.id === id ? !v.checked : v.checked }))
    },

    handleChangeCount(id, isAdd) {
      const boundary = (num, min, max) => {
        return num < min ? min : num > max ? max : num
      }
      this.list = this.list.map(v => {
        return v.id === id
          ? { ...v, count: isAdd ? boundary(v.count + 1, 1, 100) : boundary(v.count - 1, 1, 100) }
          : v
      })
    },

    handleGotoCreateOrder() {
      // 保存选择的套餐,并跳转到信息填写页面
      this.setState({ packages: this.list.filter(v => v.checked) })
      wx.navigateTo({ url: '/pages/create-order/main' })
    }
  }
}
</script>

<template>
  <div class="package-select" :class="{'hidden':!show}">
    <div @click="handleClose">close</div>
    <ul>
      <li
        v-for="v in list"
        :key="v.id"
      >
        <span class="checkbox" @click="handleCheck(v.id)">{{v.checked ? 'yes' : 'no'}}</span>
        <span class="name">{{v.name}}</span>
        <span class="price">{{v.price}}</span>
        <p>
          <span class="ctrl-btn" @click="handleChangeCount(v.id,false)">-</span>
          <span class="count">{{v.count}}</span>
          <span class="ctrl-btn" @click="handleChangeCount(v.id,true)">+</span>
        </p>
      </li>
    </ul>

    <div class="bottom-bar">
      <span class="total">{{totalPrice}}</span>
      <span @click="handleGotoCreateOrder">填写表单</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.package-select {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #fff;
  transition: all 0.25s;

  &.hidden {
    visibility: hidden;
    opacity: 0;
  }

  .ctrl-btn {
    display: inline-block;
    width: 1em;
  }
  .count {
    display: inline-block;
    width: 3em;
    text-align: center;
  }
}
</style>

